package p.ithorns.framework.idempotent;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * HttpRequestWrapper
 * 重设Request参数
 * 这里clone了请求的body；
 * 用法：1.实现Filter， 2.doFitlter方法里包装Request
 * 问题：body是私有属性, 如何保证并发请求的时候线程安全
 *
 * @author ithorns
 * @version 1.0
 * @date 2019/5/19 18:05
 */
public class HttpRequestWrapper extends HttpServletRequestWrapper {

    private final static Logger log = LoggerFactory.getLogger(HttpRequestWrapper.class);

    private final String body;

    public HttpRequestWrapper(HttpServletRequest request) {
        super(request);
        synchronized (this) {
            body = getParameterByPost(request);
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    private String getParameterByPost(HttpServletRequest req) {
        StringBuilder sbuf = new StringBuilder();
        try (
                InputStream inputStream = req.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            char[] charBuffer = new char[1024];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                sbuf.append(charBuffer, 0, bytesRead);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return sbuf.toString();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        return this.body;
    }

}
